package com.tj.redislock;


import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author tangjing
 * @date 2021/04/21 17:19
 */
@Slf4j
@Component
public class RedisLock {

    @Resource
    StringRedisTemplate template;

    public boolean tryLock(String key, String value, int expireTime, TimeUnit timeUnit) {
        Boolean flag = template.opsForValue().setIfAbsent(key, value, expireTime, timeUnit);
        if (flag == null || !flag) {
            log.info("申请锁(" + key + "," + value + ")失败");
            return false;
        }
        log.error("申请锁(" + key + "," + value + ")成功");
        return true;
    }

    public void unLock(String key, String value) {
        String currentValue = template.opsForValue().get(key);
        // 获取value和客户端唯一标识对比，满足只删除自己申请的锁
        if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
            template.opsForValue().getOperations().delete(key);
            log.info("释放锁(" + key + "," + value + ")成功");
        } else {
            log.info("释放锁(" + key + "," + value + ")失败,该锁不存在或锁已经过期");
        }
    }

}
